/**
 * Created by walkman on 2017/7/1.
 */

var server = "";
var WFB = WFB || {};

// removed from 1.9+
// if ($.browser.msie) {
//   $.ajaxSetup({cache: false});
// }

(function ($) {
  WFB.check = {
    isNickName: function (v) {
      return /^[\u4e00-\u9fa5A-Za-z0-9-_]+$/.test(v);
    },
    isClient: function () {
      return /iPhone|iPad|Android|ucweb|windows\s+mobile|Windows\s+Phone/i.test(navigator.userAgent.toLowerCase());
    },
    isIE6: window.VBArray && !window.XMLHttpRequest,
    isEmail: function (v) {
      return /^[a-z0-9][\w\.]*@([a-z0-9][a-z0-9-]*\.)+[a-z]{2,5}$/i.test(v);
    },
    isTel: function (v) {
      return /^1[34578]\d{9}$/.test(v);
    },
    isTelephone: function (v) {
      return /^0\d{2,3}-\d{5,9}$/.test(v);
    },
    isUrl: function (v) {
      return /^http:\/\/([\w-]+\.)+[\w-]+(\/[\w-.\/?%&=]*)?$/.test(v);
    },
    isNum: function (v) {
      return /^[0-9]\d*$/.test(v);
    },
    isTrueNum: function (v) {
      return /^\d+(\.\d+)?$/.test(v);
    },
    isPwd: function (v) {
      return /^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{6,20}$/.test(v);
    },
    isTradePwd: function (v) {
      return /^[0-9]{6}$/.test(v);
    },
    isName: function (v) {
      return /^[\u4e00-\u9fa5 ]{1,30}$/.test(v);
    },
    isIdCard: function (v) {
      return /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/.test(v);
    },
    isBanckCard: function (v) {
      return /^(\d{14}|\d{15}|\d{16}|\d{17}|\d{18}|\d{19}|\d{20})$/.test(v);
    }
  };
  WFB.getData = function (params) {
    var defaults = {
      dataType: "json",
      timeout: 300000,
      cache: false,
      beforeSend: function () {
        if (typeof params.beforeSendCallback == "function") {
          params.beforeSendCallback();
        }
      },
      success: function (data, textStatus, jqXHR) {
        var retCode = parseInt(data.retCode);
        if (retCode == 1 || retCode == 8001 || retCode == 8002) {
          if (typeof params.successCallback == "function") {
            params.successCallback(data, textStatus, jqXHR);
          }
        } else if (retCode == 4005) {
          if (typeof params.needLoginCallback == "function") {
            params.successCallback(data, textStatus, jqXHR);
          } else {
            location.replace("/flow/dispatch_get.do?action=doLogin");
          }
        } else {
          params.otherCodeCallback ? params.otherCodeCallback(data) : $.loadScript({
            alias: "noty",
            path: "/js/plugins/jquery/jquery.noty.packaged.min.js"
          }, function () {
            noty({
              text: data.retMsg || "数据请求异常......",
              theme: 'relax',
              type: "error",
              layout: 'bottomRight',
              timeout: 2000,//延迟关闭时间
              maxVisible: 5
            });
          });
        }
      },
      error: function (jqXHR, textStatus, errorThrown) {
        if (params.errorCallback) {
          params.errorCallback({"retMsg": "请求错误"}, jqXHR, textStatus, errorThrown);
        } else {
          if (textStatus == "timeout") {
            $.loadScript({
              alias: "noty",
              path: "/js/plugins/jquery/jquery.noty.packaged.min.js"
            }, function () {
              noty({
                text: "数据请求超时......",
                theme: 'relax',
                type: "error",//alert/warning/error/information/success消息类型
                layout: 'bottomRight',
                timeout: 2000,//延迟关闭时间
                maxVisible: 5
              });
            });
          }
        }

        /*可以通过获取一个参数jqXHR对象这些属性来判定错误来自哪个函数
         readyState
         status
         statusText
         responseXML and/or responseText
         setRequestHeader(name, value)
         getAllResponseHeaders()
         getResponseHeader()
         abort()
         */
      }
    }
    if (typeof params.ajaxSettings == "string") params.ajaxSettings = {url: params.ajaxSettings};

    //return 返回jqXHR对象,方便使用done,fail,always,then等函数
    return $.ajax($.extend(defaults, params.ajaxSettings)).done(params.afterSuccess || function () {
      });
  };

  /**
   *
   * @type {{headerLoginState: WFB.common.headerLoginState}}
   *
   *   WFB.common = {

    headerLoginState: function () {
      WFB.getData({
        ajaxSettings: "/web/loginInfo",
        successCallback: function (data) {
          var saveUserInfo = 1;
          if (data.isLogin) {
            if (location.pathname.indexOf("flow/dispatch_get.do?action=doLogin") > -1 || location.pathname.indexOf("login.html") > -1) { //如果用户已登录,直接访问登陆页面,自动跳转至我的账户
              DYC.tools.gotoBackEndDispath_GetUrl('?action=doMyAccount');
            } else {
              DYC.getData({
                ajaxSettings: {
                  url: server + "/web/auth",
                  data: {
                    method: '/user/checkSignInStatus'
                  }
                },
                successCallback: function (res) {
                  if (res.data.status == 2) {    // <a id="userAccountLoginInfo" href="'+server+'/flow/dispatch_get.do?action=doMyAccount">我的账户</a>
                    $("#login_state").html('<span class="lbl">欢迎您:' + data.personName + '</span> <i>|</i> 已签到 <a href="' + server + '/flow/dispatch_get.do?action=doLoginOut">退出</a>');
                  } else if (res.data.status == 1) {
                    $("#login_state").html('<span class="lbl">欢迎您:' + data.personName + '</span> <i>|</i> <a id="userSign" href="javascript:;">签到</a><a href="' + server + '/flow/dispatch_get.do?action=doLoginOut">退出</a>');
                  }
                  $('#userSign').click(function () {
                    if ($(this).hasClass('disabled')) return;
                    DYC.getData({
                      ajaxSettings: {
                        url: server + "/web/auth",
                        data: {
                          method: '/user/signIn'
                        }
                      },
                      successCallback: function (res2) {
                        $('#userSign').after('<div class="common_tips_top_red" ><span>◆</span>签到成功,获得' + res2.data.credits + '金币</div>');
                        $('#userSign').html('已签到').addClass('disabled');
                        setTimeout(function () {
                          $('.common_tips_top_red').fadeOut("slow")
                        }, 2000)
                      }
                    })
                  })
                }
              })
            }

            WFB.getData({
              ajaxSettings: {
                url: server + "/web/auth",
                data: {
                  method: '/account/forceOpenAccount'
                }
              },
              successCallback: function (resForceOpenAccount) {
                var forceData = $.extend(resForceOpenAccount.data, data);
                DYC.getData({
                  ajaxSettings: {
                    url: server + "/web/auth",
                    data: {
                      method: '/account/getUserAccountInfo'
                    }
                  },
                  successCallback: function (res) {
                    saveUserInfo = $.extend(res.data, forceData);
                    $.data(document.body, "login_data_user_info", saveUserInfo);
                    typeof headerLoginCallback != "undefined" && headerLoginCallback(saveUserInfo);
                    typeof menuLoginCallback != "undefined" && menuLoginCallback(saveUserInfo);
                  }
                })
              }
            })

          } else {
            typeof headerLoginCallback != "undefined" && headerLoginCallback(data);
            typeof menuLoginCallback != "undefined" && menuLoginCallback(data);
          }
          typeof menuLeftCallback != "undefined" && menuLeftCallback(data);
        }
      })
    }
  }
   */

  WFB.tools = {
    getQueryString: function (name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) {
        if (r[2].indexOf("%u") < 0) {
          r[2] = decodeURIComponent(r[2]).replace(/\\/g, "%");
        }
        return unescape(r[2]);
      }
      return null;
    },
    //格式化投资额度,金额不带逗号//已修改,修复浮点数bug,添加浮点数判断
    fmoney: function (s, n) {
      //n = n > 0 && n <= 20 ? n : 2;这种写法会被js解析为n = (n > 0 && n <= 20) ? n : 2;
      n = n > 0 && (n <= 20 ? n : 2);
      s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
      var l = s.split(".")[0].split("").reverse(),
        r = s.split(".")[1];
      t = "";
      for (var i = 0, c = l.length; i < c; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "" : "");
      }
      return t.split("").reverse().join("") + (typeof r == "undefined" ? "" : "." + r);
    },
    //首页格式化金额带逗号
    fmoneyComma: function (s, n) {
      //n = n > 0 && n <= 20 ? n : 2;这种写法会被js解析为n = (n > 0 && n <= 20) ? n : 2;
      n = n > 0 && (n <= 20 ? n : 2);
      s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
      var l = s.split(".")[0].split("").reverse(),
        r = s.split(".")[1];
      t = "";
      for (var i = 0, c = l.length; i < c; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
      }
      return t.split("").reverse().join("") + (typeof r == "undefined" ? "" : "." + r);
    },
    formatDate: function (time, format) {
      Date.prototype.format = function (format) {
        var o = {
          "M+": this.getMonth() + 1,
          // month
          "d+": this.getDate(),
          // day
          "h+": this.getHours(),
          // hour
          "m+": this.getMinutes(),
          // minute
          "s+": this.getSeconds(),
          // second
          "q+": Math.floor((this.getMonth() + 3) / 3),
          // quarter
          "S": this.getMilliseconds()
          // millisecond
        };
        if (/(y+)/.test(format) || /(Y+)/.test(format)) {
          format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
          if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
          }
        }
        return format;
      };
      return (new Date(time)).format(format);
    },
    strToType: function (str, type) {
      String.prototype.strto = function (type) {
        var ret = '';
        switch (type) {
          case 'creditType':
            ret = CREDITTYPE[this];
            break;
        }
        return ret;
      }
      return str.strto(type);
    },
    cardAddStar: function (str) {
      var resultStr = "";
      var first = str.substr(0, 6);
      var last = str.substr(str.length - 4);
      return first + "**********" + last;
    },
    formatStrSpace: function (str) {
      return str.replace(/(.{4})/g, "$1 ");
    },
    //跳转至错误页
    gotoError: function (info) {
      window.location.href = "/error.html?info=" + coverStringToUniCode(info);
    },
    gotoTransmitUrl: function (transmitPage, info) {
      window.location.href = "/transmit.html?transmitPage=" + transmitPage + "&info=" + coverStringToUniCode(info);
    },
    gotoFrontEndUrl: function (url) {
      window.location.href = url;
    },
    gotoBackEndUr: function (url) {
      window.location.href = server + url;
    },
    gotoBackEndDispath_GetUrl: function (url) {
      window.location.href = server + "/flow/dispatch_get.do" + url;
    }
  }
  WFB.formula = {
    fincome: function (result, num) {
      var index = result.toString().indexOf('.');
      var result2;
      if (index > -1) {
        result2 = result.toString().substr(0, index + num + 1);
        if (result2.substr(index).length < 3) {
          result2 = result2 + "0";
        }
      } else {
        result2 = result.toString() + ".00";
      }
      return result2;
    },
    calculate: function (amount, rate, time) {//收益计算：预计收益=投资金额*年收益率*天数/365
      if (!amount) return;
      var result = "" + accDiv(accMul(accMul(amount, rate), time), 365 * 100);
      return DYC.formula.fincome(result, 2);
    },
    calculate2: function (amount, rate, duration) {
      if (!amount) return;
      var money = amount;
      var month = parseFloat(DYC.formula.fincome(rate / 12, 16));
      var mpow = Math.pow((1 + month), duration);
      var preincome = DYC.formula.fincome((money * month * mpow) / (mpow - 1), 2) * duration - money;
      if (preincome < 0) {
        return DYC.formula.fincome(0.00, 2);
      }
      return DYC.formula.fincome(preincome, 2);
    },
    calculate3: function (amount, rate, duration, durationType) {
      if (!amount) return;
      var money = amount;
      var durationType2;
      if (durationType == 1 || durationType == 2) {
        durationType2 = 1;
      } else if (durationType == 3) {
        durationType2 = 3;
      } else if (durationType == 4) {
        durationType2 = 6;
      }
      var preincome = DYC.formula.fincome(money * rate * durationType2 / 12, 2) * duration;
      return DYC.formula.fincome(preincome, 2);
    },
    calculate2_month: function (amount, rate, duration) {
      if (!amount) return;
      var money = amount;
      var month = parseFloat(DYC.formula.fincome(rate / 12, 16));
      var mpow = Math.pow((1 + month), duration);
      var preincome = (money * month * mpow) / (mpow - 1);
      return DYC.formula.fincome(preincome, 2);
    },
    calculate3_month: function (amount, rate, durationType) {
      if (!amount) return;
      var money = amount;
      var durationType2;
      if (durationType == 1 || durationType == 2) {
        durationType2 = 1;
      } else if (durationType == 3) {
        durationType2 = 3;
      } else if (durationType == 4) {
        durationType2 = 6;
      }
      var preincome = money * rate * durationType2 / 12;
      return DYC.formula.fincome(preincome, 2);
    }
  };
  //js浮点运算有bug,方法可再优化,避免使用的多层嵌套
  /* 除 */
  function accDiv(arg1, arg2) {
    var t1 = 0, t2 = 0, r1, r2;
    try {
      t1 = arg1.toString().split(".")[1].length
    } catch (e) {
    }
    try {
      t2 = arg2.toString().split(".")[1].length
    } catch (e) {
    }
    with (Math) {
      r1 = Number(arg1.toString().replace(".", ""))
      r2 = Number(arg2.toString().replace(".", ""))
      return (r1 / r2) * pow(10, t2 - t1);
    }
  }

  /* 乘 */
  function accMul(arg1, arg2) {
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try {
      m += s1.split(".")[1].length
    } catch (e) {
    }
    try {
      m += s2.split(".")[1].length
    } catch (e) {
    }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
  }

  function coverStringToUniCode(str) {
    return escape(str);
  }

  function coverUnicodeToString(str) {
    str = eval(str);
    str = unescape(str.replace(/\u/g, "%u"));
    return str + "";
  }

  function coverUnicodeToString2(str) {
    //str = eval(str);
    str = unescape(str.replace(/\u/g, "%u"));
    return str + "";

  }

  function refreshIE() {

  }

})(jQuery);


//动态加载js
(function ($) {
  var scriptObj = {};

  $.loadScript = function (file, doneCallback) {//file:{alias:"xxx",path:"xx/xx/xxx.js"}
    var script = scriptObj[file.alias];

    if (!script) {
      //简单的判断js是否在页面已经引入
      var $exist = $("script").filter(function () {
        return $.trim($(this).attr("src")) == file.path;
      });

      if ($exist.length > 0) {
        scriptObj[file.alias] = {
          readyState: "loaded",
          queue: []
        }
        doneCallback && doneCallback();
      } else {
        scriptObj[file.alias] = {
          readyState: "loading",
          queue: doneCallback ? [doneCallback] : []
        }

        var script = document.createElement("script");
        script.type = "text/javascript";
        script.language = "javascript";
        script.src = file.path;
        script.onload = script.onreadystatechange = function () {
          if (!script.readyState || script.readyState == "loaded" || script.readyState == "complete") {
            script.onload = script.onreadystatechange = null;

            scriptObj[file.alias].readyState = "loaded";

            var queue = scriptObj[file.alias].queue;

            while (queue.length > 0) {
              queue[0]();
              queue.shift();
            }
          }
        };
        document.getElementsByTagName("head")[0].appendChild(script);
      }

      /*外链跨域
       * $.ajax({
       dataType: "script",
       url: file.path,
       cache:true
       }).done(function(response){
       scriptObj[file.alias].readyState = "loaded";
       var queue = scriptObj[file.alias].queue;
       while(queue.length>0){
       queue[0]();
       queue.shift();
       }
       });*/
    } else {
      if (scriptObj[file.alias].readyState == "loading") {
        doneCallback && scriptObj[file.alias].queue.push(doneCallback);
      } else {//loaded
        var fn_queue = scriptObj[file.alias].queue;
        if (fn_queue > 0) {
          scriptObj[file.alias].queue.push(doneCallback);//不知道会不会出现这里判断存在队列,与执行不同步的问题存在
        } else {
          doneCallback && doneCallback();
        }
      }
    }
  };

})(jQuery)
